package com.shishuo.cms.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TextUtil {
	public static String readTxtFile(String filePath) {
		StringBuffer retString = new StringBuffer();
		try {
			String encoding = "GBK";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					retString.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return retString.toString();
	}

	private static List<String> getAllTxtPath(String templatePath) {
		List<String> txtList = new ArrayList<String>();
		File dir = new File(templatePath);
		File[] files = dir.listFiles();
		if (null != files) {
			for (File file : files) {
				if (!file.isDirectory()) {
					txtList.add(file.getAbsolutePath());
				}
			}
			return txtList;
		}
		return null;
	}

	public static void main(String[] args) {
		List<String> allTxtPathList = getAllTxtPath("F:\\txt\\source");
		for (int i = 0; i < allTxtPathList.size(); i++) {
			StringBuffer retString = new StringBuffer();
			try {
				String encoding = "GBK";
				File file = new File(allTxtPathList.get(i));
				if (file.isFile() && file.exists()) { // 判断文件是否存在
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(file), encoding);// 考虑到编码格式
					BufferedReader bufferedReader = new BufferedReader(read);
					String lineTxt = null;
					int j = 0;
					while ((lineTxt = bufferedReader.readLine()) != null) {
						retString.append(lineTxt);
						j++;
						if (retString.length() > 1000) {
							writeToFile(allTxtPathList.get(i), j,retString.toString());
							retString = new StringBuffer();
						}
					}
					read.close();
				} else {
					System.out.println("找不到指定的文件");
				}
			} catch (Exception e) {
				System.out.println("读取文件内容出错");
				e.printStackTrace();
			}
		}
	}

	public static void writeToFile(String file,int j, String txt) {
		try {
			file=file.replace("source", "target")+j+".txt";
			FileOutputStream os = new FileOutputStream(new File(file), true);
			os.write((txt + "\n").getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
